//
//  AppDelegate.m
//  ForYourBeauty
//
//  Created by Kelly xu on 2019/5/21.
//  Copyright © 2019 changrenTech. All rights reserved.
//

#import "AppDelegate.h"
#import "BeautyLightTabbarViewController.h"
#import "LoginViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import <VisitorSDK_HSFramework/CSManager.h>
#import <Reachability/Reachability.h>
#import <SystemConfiguration/SCNetworkReachability.h>
@interface AppDelegate ()<CBCentralManagerDelegate,CBPeripheralDelegate>{
    
}
@property(nonatomic,strong)CBCentralManager *centralManager;
@property (nonatomic, strong) Reachability *reachability;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    // Override point for customization after application launch.
    [[LKAlarmMamager shareManager] didFinishLaunchingWithOptions:launchOptions];
    [[LKAlarmMamager shareManager] registDelegateWithObject:self];
    [self config];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    if (EC_ISNullStr([LoginTools sharedTools].token)) {
        LoginViewController *logVC = [[LoginViewController alloc]init];
        RTRootNavigationController *nav = [[RTRootNavigationController alloc]initWithRootViewController:logVC];
        [self.window setRootViewController:nav];
        [self.window makeKeyAndVisible];
    }else{
        BeautyLightTabbarViewController *tabVC = [[BeautyLightTabbarViewController alloc]init];
        RTRootNavigationController *nav = [[RTRootNavigationController alloc]initWithRootViewControllerNoWrapping:tabVC];
        [self.window setRootViewController:nav];
        [self.window makeKeyAndVisible];
    }
    NSLog(@"______________%@",[WifiUtils getWifiName]);
    //启动53Service
    [CSManager setup53ServiceWithArg:@"10034819" style:@"1"];
    //注册远程通知
    [self setRomoteNotifi];
    return YES;
}
-(void)config{
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    [self configureKeyboardManager];
    [self AFNReachability];
}

//使用AFN框架来检测网络状态的改变
-(void)AFNReachability
{
    //1.创建网络监听管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    //2.监听网络状态的改变
    /*
     AFNetworkReachabilityStatusUnknown     = 未知
     AFNetworkReachabilityStatusNotReachable   = 没有网络
     AFNetworkReachabilityStatusReachableViaWWAN = 3G
     AFNetworkReachabilityStatusReachableViaWiFi = WIFI
     */
    //3.开始监听
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G");
                [[NSNotificationCenter defaultCenter]postNotificationName:@"needToBindDevice" object:nil];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                [[NSNotificationCenter defaultCenter]postNotificationName:@"needToBindDevice" object:nil];
                break;
                
            default:
                break;
        }
    }];
}

/// 配置键盘管理器
- (void)configureKeyboardManager {
    IQKeyboardManager.sharedManager.enable = YES;
    IQKeyboardManager.sharedManager.enableAutoToolbar = NO;
    IQKeyboardManager.sharedManager.shouldResignOnTouchOutside = YES;
}
#pragma mark - 推送 ---------------start-----------------------
- (void)setRomoteNotifi{
    //注册通知
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert categories:nil]];
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    if (notificationSettings.types != UIUserNotificationTypeNone) {
        [application registerForRemoteNotifications];
    }
}
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
    [[LKAlarmMamager shareManager] handleOpenURL:url];
    return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [CSManager close53Service];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"cancleTimeCounter" object:nil];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [CSManager open53Service];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [CSManager handleAppTerminate];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"callUpTimeCounter" object:nil];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [CSManager registerDeviceToken:deviceToken];
}
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [[LKAlarmMamager shareManager] didReceiveLocalNotification:notification];
}
- (void)centralManagerDidUpdateState:(nonnull CBCentralManager *)central {
    switch (central.state) {
        case CBManagerStateUnknown:
            NSLog(@">>>初始的时候是未知的（刚刚创建的时候）");
            break;
        case CBManagerStateResetting:
            NSLog(@">>>正在重置状态");
            break;
        case CBManagerStateUnsupported:
            NSLog(@">>>设备不支持的状态");
            break;
        case CBManagerStateUnauthorized:
            NSLog(@">>>设备未授权状态");
            break;
        case CBManagerStatePoweredOff:
            NSLog(@">>>设备关闭状态");
            break;
        case CBManagerStatePoweredOn:
        {
            NSLog(@">>>设备开启状态 -- 可用状态");
        }
            break;
        default:
            break;
    }
}
-(void)lk_receiveAlarmEvent:(LKAlarmEvent *)event
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"接受到通知！" message:event.title preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [KeyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}
@end
